package com.syxd.controller;

import com.sun.org.apache.regexp.internal.RE;
import com.syxd.common.annotation.LogOperation;
import com.syxd.common.constant.Constant;
import com.syxd.common.entity.WebResult;
import com.syxd.common.exception.ErrorCode;
import com.syxd.common.utils.HttpContextUtils;
import com.syxd.common.utils.MD5Util;
import com.syxd.common.utils.PageData;
import com.syxd.dto.SysUserDTO;
import com.syxd.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("sys/sysuser")
@Api(tags = "用户管理")
public class sysUserController {
    @Autowired
    SysUserService sysUserService;
    @PostMapping("page")
    @ApiOperation("分页")
    @LogOperation(apiType = "sysuser",apiPath = "sys/sysuser/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String"),
            @ApiImplicitParam(name = "userId", value = "用户id", paramType = "query", dataType="String"),
            @ApiImplicitParam(name = "loginAccount", value = "账号", paramType = "query", dataType="String"),
            @ApiImplicitParam(name = "userRoleId", value = "角色id", paramType = "query", dataType="String"),
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "query", dataType="String"),
            @ApiImplicitParam(name = "userState",value = "用户状态（0，1）",paramType = "query", dataType="String")
    })
    @RequiresPermissions("sys:sysuser:page")
    public WebResult<PageData<SysUserDTO>> page(@ApiIgnore @RequestBody Map<String, Object> params){
        PageData<SysUserDTO> page = sysUserService.page(params);

        return new WebResult<PageData<SysUserDTO>>().ok(page);
    }
    @GetMapping("getUserPermissions")
    @ApiOperation("获取当前用户权限")
    @LogOperation(apiType = "sysuser", apiPath = "sys/sysuser/getUserPermissions")
    public WebResult getUserPermissions(HttpServletRequest request) {
        //String token = HttpContextUtils.getToken(request);
       String token = request.getHeader(Constant.TOKEN_HEADER);
        if (StringUtils.isBlank(token)) {
            new WebResult<>().error(ErrorCode.TOKEN_INVALID);
        }
        return sysUserService.getUserPermissionsByToken(token);
    }

    @PostMapping("login")
    @ApiOperation("登陆")
    @LogOperation(apiType = "sysuser", apiPath = "sys/sysuser/login")
    public WebResult login(@RequestBody SysUserDTO login, HttpServletResponse response) {
        WebResult result = sysUserService.login(response, login);

        return result;
    }

    @GetMapping("logout")
    @ApiOperation("登出")
    @LogOperation(apiType = "sysuser", apiPath = "sys/sysuser/logout")
    public WebResult logout(HttpServletRequest request) {
        return sysUserService.logout(request);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation(apiType = "sysuser",apiPath = "sys/sysuser")
    @RequiresPermissions("sys:sysuser:save")
    public WebResult save(@RequestBody SysUserDTO dto,HttpServletRequest request){
        WebResult result = new WebResult();
        //效验数据
        List<SysUserDTO> sysUserDTOS = sysUserService.selectByLoginAccount(dto.getLoginAccount());
        if (sysUserDTOS != null && sysUserDTOS.size()>0) {
            return result.error(ErrorCode.ACCOUNT_EXISTS);
        }
        String loginPassword = dto.getLoginPassword();
        if(StringUtils.isNotBlank(loginPassword)){

            dto.setLoginPassword(MD5Util.md5(loginPassword));
        }
        dto.setLoginPassword(MD5Util.md5(loginPassword));
        Integer userId = Integer.valueOf((String) sysUserService.getInfoFromToken(request,"userId").getData());
        dto.setCreateBy(userId);
        sysUserService.saveInfo(dto);

        return result;
    }
    @PutMapping
    @ApiOperation("修改")
    @LogOperation(apiType = "sysuser",apiPath = "sys/sysuser")
    @RequiresPermissions("sys:sysuser:update")
    public WebResult update(@RequestBody SysUserDTO dto,HttpServletRequest request){
        //效验数据
        String confirmPassword = dto.getConfirmPassword();
        if(StringUtils.isNotBlank(confirmPassword)){

            dto.setLoginPassword(MD5Util.md5(confirmPassword));
        }
        Integer userId = Integer.valueOf((String) sysUserService.getInfoFromToken(request,"userId").getData());
        dto.setUpdateBy(userId);
        sysUserService.update(dto);

        return new WebResult();
    }
    @PostMapping("changPassword")
    @ApiOperation("修改密码")
    @LogOperation(apiType = "sysuser",apiPath = "sys/sysuser/changPassword")
    @RequiresPermissions("public:sysuser:update")
    public WebResult changPassword(@RequestBody SysUserDTO sysUserDTO,HttpServletRequest request) {
        Integer userId = Integer.valueOf((String) sysUserService.getInfoFromToken(request,"userId").getData());
        sysUserDTO.setUpdateBy(userId);
        return sysUserService.changePassword(sysUserDTO,request);
    }
    @GetMapping("{id}")
    @ApiOperation("信息")
    @LogOperation(apiPath = "sys/sysuser/id",apiType = "sysuser")
    @RequiresPermissions("sys:sysuser:info")
    public WebResult<SysUserDTO> get(@PathVariable("id") Long id){
        SysUserDTO data = sysUserService.get(id);

        return new WebResult<SysUserDTO>().ok(data);
    }
    @DeleteMapping("{id}")
    @ApiOperation("删除")
    @LogOperation(apiType = "sysuser",apiPath = "sys/sysuser")
    @RequiresPermissions("sys:sysuser:delete")
    public WebResult delete(@PathVariable("id") Long id,HttpServletRequest request){
        Integer userId = Integer.valueOf((String) sysUserService.getInfoFromToken(request,"userId").getData());

        Long[] ids = new Long[1];
        ids[0]=id;

        sysUserService.delete(ids,userId);

        return new WebResult();
    }
    @GetMapping
    @ApiOperation("获取用户信息")
    @LogOperation(apiPath = "sys/sysuser",apiType = "sysuser")
    @RequiresPermissions("public:sysuser:info")
    public WebResult<SysUserDTO> getUserInfo(HttpServletRequest request){
        Integer userId = Integer.valueOf((String) sysUserService.getInfoFromToken(request,"userId").getData());

        SysUserDTO data = sysUserService.get(userId.longValue());

        return new WebResult<SysUserDTO>().ok(data);
    }
}
